function [idxTrain,idxTest] = generate_cv_samples_permutation(sample,pm,seed,split,savedir,fbase)
% This function generates wave-specific training and testing sets from the
% full sample. We save these sets for out-of-sample performance analysis. 

% Inputs: 
% (1) sample: cross-sectional dataset with electricity consumption, 
% covariates, and propensity scores
% (2) pm: number permutations
% (3) seed: seed for random split between test and training set
% (4) split: share of data in the testing set
% (5) savedir: directory for saving indices
% (7) fbase: string used to indicate the propensity score and baseline
% months specification  

% Outputs: 
% (1) idxTrain: index of observations in the training set
% (2) idxTest: index of observations in the testing set

%% Generate training set and testing sets 
idxTrain=nan(size(sample,1),pm);
idxTest=nan(size(sample,1),pm);

for i=1:pm
    rng(seed(i));
    G = findgroups(sample.opower_paper_wave,sample.opower); %stratify by treatment status and opower wave
    c = cvpartition(G,'Holdout',split,'Stratify',true); 
    idxTrain(:,i)=training(c);
    idxTest(:,i)=test(c);
end

%% Add Column names to arrays 
idxTrain=array2table_with_name(idxTrain, 'perm');
idxTest=array2table_with_name(idxTest, 'perm');

end